// 路径  /users/
var express = require('express');
var router = express.Router();
var { userModel } = require('../model/model')
const Core = require('@alicloud/pop-core'); // 引入阿里云 SDK

const jwt = require('jsonwebtoken')
/* GET users listing. */
// 阿里云短信验证
const client = new Core({ // 创建 Client 对象
  accessKeyId: 'LTAI5tDnzbKgAfZRwqRAqWPp', // 替换成自己的 AccessKey ID
  accessKeySecret: 'Pt9BBDlmxWfhiYYY5atYcreVa1cAWv', // 替换成自己的 AccessKey Secret
  endpoint: 'https://dysmsapi.aliyuncs.com', // API 访问入口，根据实际情况修改
  apiVersion: '2017-05-25' // API 版本号，根据实际情况修改
});

let yanzhengma = {}
// 生成随机验证码
function generateCode() {
  const code = Math.floor(Math.random() * (9999 - 1000 + 1)) + 1000;
  // yanzhengma = code.toString()
  return code.toString();
}

//发送验证码
router.post('/sendYzm', async (req, res) => {

  const { phone } = req.body;
  console.log('进入发送验证码接口，接收到的请求数据：', req.body);
  const code = generateCode(); // 生成验证码
  yanzhengma[phone] = code // 找回密码的校验，yanzhengma存储的是生成的验证码
  const params = {
    "RegionId": "cn-hangzhou", // 短信服务所在区域，可以参考阿里云文档
    "PhoneNumbers": phone, // 目标手机号码
    "SignName": "小智1234", // 短信签名名称，需先在阿里云控制台中申请审核通过
    "TemplateCode": "SMS_480305085", // 短信模板 CODE，需先在阿里云控制台中申请审核通过
    "TemplateParam": JSON.stringify({ // 短信模板参数，为 JSON 字符串格式
      "code": code // 模板中的变量名和对应的值
    })
  };
  const requestOption = { method: 'POST' };
  client.request('SendSms', params, requestOption).then((result) => {
    console.log(result.Code);

    if (result.Code == 'OK') {

      res.send({    // 返回状态码和生成的验证码
        message: '验证码已发送，请注意查收！',
        code: 200
      })
    } else {
      res.send({
        message: '短信发送失败，请稍后重试！'
      });
    }

  })
    .catch((ex) => {
      console.log(ex.data.Message, "ex");

      res.send({
        data: ex,
        code: 201
      });
    })
})
// 注册
router.post('/register', async (req, res) => {
  const { phone, passWord, code } = req.body;

  // 验证验证码
  if (yanzhengma[phone] !== code) {
    return res.send({
      code: 400,
      msg: "验证码错误",
      data: null
    });
  }
  // 检查手机号是否已注册
  const existingUser = await userModel.findOne({ phone });
  if (existingUser) {
    return res.send({
      code: 400,
      msg: "该手机号已注册",
      data: null
    });
  }
  const newUser = new userModel({
    phone,
    passWord
  });
  try {
    await newUser.save();
    // 注册成功后删除验证码
    delete yanzhengma[phone];
    res.send({ code: 200, msg: "注册成功", data: newUser });
  } catch (error) {

    res.send({
      code: 500,
      msg: "注册失败，请稍后重试",
      data: null
    });
  }

});
//密钥
// 访问令牌有效期
const ACCESS_TOKEN_SECRET = '1h'
//刷新令牌有效期
const REFRESH_TOKEN_SECRET = '30d'

//生成Token
function generateTokens(user) {
  const accessToken = jwt.sign({ userId: user._id }, ACCESS_TOKEN_SECRET, { expiresIn: '1h' });
  const refreshToken = jwt.sign({ userId: user._id }, REFRESH_TOKEN_SECRET, { expiresIn: "30d" });
  return { accessToken, refreshToken }
}
//登录
router.post('/login', async (req, res) => {
  const { phone, passWord } = req.body;
  const data = await userModel.findOne({ phone });
  if (data) {
    if (data.passWord === passWord) {
      const tokens = generateTokens(data)
      res.send({
        code: 200, msg: '登录成功', data: {
          user: data,
          accessToken: tokens.accessToken,
          refreshToken: tokens.refreshToken
        }

      });
    } else {
      res.send({ code: 400, msg: "手机号或密码错误", data: null });
    }
  } else {
    res.send({ code: 401, msg: "用户不存在", data: null });
  }
});


module.exports = router;
